const mongoose = require("mongoose");
const Test = require("../models/testModel");

//增加试卷
exports.createTest = async (req, res) => {
  try {
    const newTest = await Test.create(req.body);
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newTest,
    });
  } catch (err) {
    console.log("创建试卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//删除试卷（不提供这个功能)
exports.deleteTest = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const data = await Test.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      data: data,
    });
  } catch (err) {
    console.log("删除试卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改试卷
exports.updateTest = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const newTest = await Test.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!newTest) {
      return res.status(404).json({
        message: "修改的试卷并不存在",
      });
    }
    res.status(200).json({
      status: "success",
      data: newTest,
    });
  } catch (err) {
    console.log("修改试卷失败", err);
    res.status(404).json({
      err,
    });
  }
};

//获取所有试卷
exports.getAllTest = async (req, res) => {
  try {
    const testList = await Test.find();
    res.status(200).json({
      status: "success",
      data: testList,
    });
  } catch (err) {
    console.log("获取所有试卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//获取正在发布试卷
exports.getPublishingTest = async (req, res) => {
  try {
    const test = await Test.find({ type: "publishing" });
    res.status(200).json({
      status: "success",
      data: test,
    });
  } catch (err) {
    console.log("获取正在发布试卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//发布试卷 unpublish 未发布  publishing 正在发布  published 已发布
exports.publishTest = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.body._id);

    // 将原来publishing变为published   重置
    await Test.updateMany(
      { type: "publishing" },
      { $set: { type: "published" } }
    );

    await Test.updateOne({ _id: id }, { $set: { type: "publishing" } });

    const newTestList = await Test.find();

    res.status(200).json({
      status: "success",
      data: newTestList,
    });
  } catch (err) {
    console.log("试卷发布失败", err);
    res.status(404).json({
      err,
    });
  }
};

//获取全部已发布试卷标题（已发布+发布中)
exports.getPublishedTest = async (req, res) => {
  try {
    const test = await Test.find(
      { type: { $in: ["publishing", "published"] } },
      { title: 1, _id: 0 }
    );
    res.status(200).json({
      status: "success",
      data: test,
    });
  } catch (err) {
    console.log("获取已发布试卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};
